<?php
namespace App\Http\Controllers\UserCenter;

use App\Http\Controllers\Controller;
use App\Admin\Eloquent\ProjectsUser;
use App\Admin\Eloquent\ProjectProfit;
use App\Admin\Eloquent\GiftActivity;
use App\Admin\Eloquent\Code;
use App\Admin\Eloquent\OrganizationalUser;
use App\Admin\Eloquent\Information;
use App\Admin\Eloquent\Profit;
use App\Admin\Eloquent\ProfitRole;
use App\Eloquent\Projects;
use App\Eloquent\User;
use App\Admin\Eloquent\UserInfo;
use App\Eloquent\ProjectCheck;
use App\Extensions\Pagination\BoosstrapPageUser;
use App\Extensions\Pagination\BoosstrapPageProject;
use App\Admin\Eloquent\GiftReceive;
use App\Eloquent\ProjectAttr;
use Illuminate\Support\Facades\Hash;
use App\Eloquent\TradeRecords;
use Illuminate\Http\Request;
use DB;
use Log;
use Exception;
use CreateSingleHostingPayTrade;
use CreateBatchHostingPayTrade;
use FinishPreAuthTrade;
use CreateSingleHostingPayToCardTrade;

/**
 * 担保机构
 */
class GuaranteeController extends Controller{
  public function init(){
    $user = User::user();
    $user->checkRole('GuaranteeAgency');
  }
  public function index(Request $request){
    // GiftActivity::sendGift('gift_grant_rule_1',8490,date('Y-m-d'),1000);
    $find=$request->all();
    $user = User::user();
    $list=Projects::whereNotIn('status',['none','stop'])->orderBy('created_at','desc')->where('collateral_id',$user->id);
    if(isset($find['status']) && !empty($find['status'])){
      $list->where('status',$find['status']);
    }
    if(isset($find['sn'])){
      $list->where('status','like','%'.$find['sn'].'%');
    }
    if(isset($find['begin_time']) && !empty($find['begin_time'])){
      $list->where('start_time','>=',$find['begin_time']);
    }
    if(isset($find['end_time']) && !empty($find['end_time'])){
      $list->where('end_time','<=',$find['end_time']);
    }
    $list=$list->paginate(8);
    $links = (new BoosstrapPageUser($list))->render();

    $status=Code::getByTypeId('project_status');

  	return view('web.guarantee.index',compact('list','links','status','find'));
  }
  /**
   * 封包
   * @return [type] [description]
   */
  public function check($id){
    $project=Projects::find($id);
    //可以使用的红包
    $grant_rule='gift_grant_rule_3';
    if($project->new_projects){
      $grant_rule='gift_grant_rule_8';
    }
    $gift=GiftActivity::where(['cate_id'=>$project->gift_cate,'status'=>1])->where('grant_rule',$grant_rule)->where('begin_time','<=',date('Y-m-d H:i:s'))->value('name');
    $invest=ProjectsUser::where('projects_id',$id)->orderBy('invest_time','desc')->paginate(8);
    $links = (new BoosstrapPageProject($invest))->render();
    $type_attr=ProjectAttr::where('project_id','=',$project->id)->get();
    $project_check=ProjectCheck::join('users','users.id','=','project_check.check_user')->where('project_check.project_id',$id)->get();
    return view('web.guarantee.check',compact('project','invest','type_attr','links','project_check','gift'));
  }
  /**
   * 封包项目
   * @param  [type] $id [description]
   * @return [type]     [description]
   */
  public function checkProject(Request $q,$id){
    $data=$q->all();
    $time=date('Y-m-d H:i:s');
    $login_user=User::user();
    //验证登录密码
    if(!Hash::check(md5($data['password']),$login_user->password)){abort(600,'密码错误');}
    $project=Projects::find($id);
    //判断项目是否生成合同
    if(empty($project->projects_file)){abort(600,'未生成合同');}
    //判断项目是否达到满标条件
    if(!$project->checkFull()){abort(600,'未达到满标条件');}
    $project_user=ProjectsUser::where('projects_id',$id)->get();
    // 判断是否代收完成
    $trade=TradeRecords::where(['project_id'=>$id,'status'=>3])->count();
    if($trade<$project_user->count()){
      abort(600,'代收投资金未完成');
    }
    //融资人手续费
    $lv=explode(',',Code::where(['code'=>'service_pot_withdraw'])->value('description'));
    $user_fee=$lv[1];

    $profit=Profit::find($project->profits_cate);//分润规则
    $profit_role=ProfitRole::where('profit_id',$profit->id)->get();//分润角色
    $financier=User::find($project->financier_id);//融资人
    $code_date=Code::find('repayment_day')->description;//系统设置的还款日期
    $project_profit=array();//分润记录
    $profit_row=array('project_id'=>$project->id,'money'=>0,'pay_time'=>null,'status'=>0,'input_time'=>$time,'profit'=>0,'broker_code'=>'','project_user_id'=>0);//初始化分润记录
    $total_profit=$project->financeTime($project->rate);//融资人应还的总利息
    $money_marketing_agency1=0;//营销机构实际的总利息
    $money_marketing_agency=$project->financeTime($profit_role->where('stage','profits_stage_one')->where('role','MarketingAgency')->pluck('scale')->get(0));//营销机构应得的总利息
    $bbl_user=User::find(2);//平台账户
    //新浪参数
    $trade_list=array();
    $trade_saving_sub=array(2=>'UID',3=>'SAVING_POT',5=>'');
    $trade_basic_sub=array(2=>'UID',3=>'BASIC',5=>'');
    //支付流水记录
    $trade_data=array();
    $trade_sub=array('type'=>'1','project_id'=>$project->id,'pay_user'=>$project->financier_id,'created_at'=>$time,'pay_time'=>$time,'status'=>1,'user_fee'=>0);
    
    //第一阶段分润,担保机构
    $item=$profit_role->where('stage','profits_stage_one')->where('role','GuaranteeAgency')->first();
    $money=$project->financeTime($item->scale);
    $user=User::find($project->collateral_id);
    $orgnaize_user=OrganizationalUser::where('user_id',$user->id)->first();
    
    $profit_new_row=$profit_row;
    $sn=createSn();
    $profit_new_row['sn']=$sn;
    $profit_new_row['type']=2;
    $profit_new_row['pay_time']=$time;
    $profit_new_row['status']=1;
    $profit_new_row['user_id']=$user->id;
    $profit_new_row['user_name']=$orgnaize_user->company_name;
    $profit_new_row['role_slug']=$item->role;
    $profit_new_row['broker_code']=$user->broker_code;
    $profit_new_row['money']=$money;
    if($money>0){
      $project_profit[]=$profit_new_row;
    }

    $new_ar=$trade_basic_sub+array(0=>$sn,1=>$user->identity_id,4=>$money,6=>'担保机构分润');
    ksort($new_ar);
    if($money>0){
      $trade_list[]=$new_ar;
      $trade_data[]=array_merge($trade_sub,array('sn'=>$sn,'receive_user'=>$user->id,'money'=>$money,'remarks'=>'担保机构分润'));
    }

    //第一阶段，营销机构
    $profit_new_row=$profit_row;
    $profit_new_row['type']=2;
    $profit_new_row['pay_time']=$time;
    $profit_new_row['status']=1;
    $item=$profit_role->where('stage','profits_stage_one')->where('role','MarketingAgency')->first();
    $role=$project_user->lists('org_code')->unique();
    $orgnaize=OrganizationalUser::whereIn('code',$role)->get();//所有投资人的营销机构
    foreach ($orgnaize as $row) {
      foreach ($project_user as $puser) {
        if($puser->org_code==$row['code']){
          $ratio=$row->profit_ratio;
          $project_user_info=Userinfo::where('user_id',$puser->user_id)->first();//投资人
          //二级经纪人
          $second_broker=$user_info=UserInfo::where('invite_code',$puser->second_broker_code)->first();
          // 判断二级经纪人是否存在,是否含有分成比例,并且要设置支付密码
          if(!empty($user_info) && $project_user_info->invite_code!=$project_user_info->second_broker_code && $row->second_radio!=-1 && $user_info->is_set_pay_password){
            $user=User::find($user_info->user_id);
            $money2=$project->financeTime($row->second_radio,$puser->invest_money);
            $sn=createSn();
            $profit_new_row['sn']=$sn;
            $profit_new_row['user_id']=$user->id;
            $profit_new_row['user_name']=$user->userInfo->name;
            $profit_new_row['role_slug']='User';
            $profit_new_row['broker_code']=$user->userInfo->broker_code;
            $profit_new_row['project_user_id']=$puser->id;
            $profit_new_row['money']=$money2;
            $money_marketing_agency1+=$money2;
            if($money2>0){
              $project_profit[]=$profit_new_row;
            }
            $new_ar=$trade_saving_sub+array(0=>$sn,1=>$user->identity_id,4=>$money2,6=>'二级经纪人分润');
            ksort($new_ar);
            if($money2>0){
              $trade_list[]=$new_ar;
              $trade_data[]=array_merge($trade_sub,array('sn'=>$sn,'receive_user'=>$user->id,'money'=>$money2,'remarks'=>'二级经纪人分润'));
            }
          }
          
          //经纪人
          $user_info=UserInfo::where('invite_code',$puser->broker_code)->first();
          // 判断经纪人是否含有分成比例,并且经纪人要设置支付密码
          if($row->profit_ratio!=-1 && $user_info->is_set_pay_password){
            //如果(不存在二级经纪人或者自己是二级经纪人),并且有分润比例
            if((empty($second_broker) || $project_user_info->invite_code==$project_user_info->second_broker_code) && $row->second_radio>0){
              $ratio=$row->second_radio+$row->profit_ratio;
            }
            $money1=$project->financeTime($ratio,$puser->invest_money);
            $sn=createSn();
            $profit_new_row['sn']=$sn;
            $profit_new_row['user_id']=$user_info->user_id;
            $profit_new_row['user_name']=$user_info->name;
            $profit_new_row['role_slug']='Agent';
            $profit_new_row['broker_code']=$user_info->broker_code;
            $profit_new_row['project_user_id']=$puser->id;
            $profit_new_row['money']=$money1;
            $money_marketing_agency1+=$money1;
            if($money1>0){
              $project_profit[]=$profit_new_row;
            }
            $new_ar=$trade_saving_sub+array(0=>$sn,1=>$user->identity_id,4=>$money1,6=>'经纪人分润');
            ksort($new_ar);
            if($money1>0){
              $trade_list[]=$new_ar;
              $trade_data[]=array_merge($trade_sub,array('sn'=>$sn,'receive_user'=>$user->id,'money'=>$money1,'remarks'=>'经纪人分润'));
            }
          }
          //判断营销机构是否含有自身分润比例
          $row_user=User::find($row->user_id);
          if($row->org_profit!=-1){
            $money=$project->financeTime($row->org_profit,$puser->invest_money);
          }else{
            $money=$project->financeTime($item->scale,$puser->invest_money);
          }
          $sn=createSn();
          $profit_new_row['sn']=$sn;
          $profit_new_row['user_id']=$row->user_id;
          $profit_new_row['user_name']=$row->company_name;
          $profit_new_row['role_slug']='MarketingAgency';
          $profit_new_row['project_user_id']=$puser->id;
          $profit_new_row['broker_code']=null;
          $profit_new_row['money']=$money;
          if($money>0){
            $project_profit[]=$profit_new_row;
          }
          $money_marketing_agency1+=$money;
          
          $new_ar=$trade_saving_sub+array(0=>$sn,1=>$row_user->identity_id,4=>$money,6=>'营销机构分润');
          ksort($new_ar);
          if($money>0){
            $trade_list[]=$new_ar;
            $trade_data[]=array_merge($trade_sub,array('sn'=>$sn,'receive_user'=>$row->user_id,'money'=>$money,'remarks'=>'营销机构分润'));
          }
        }
      }
    }

    //第一阶段，运营平台
    $profit_new_row=$profit_row;
    $sn=createSn();
    $profit_new_row['sn']=$sn;
    $profit_new_row['type']=2;
    $profit_new_row['pay_time']=$time;
    $profit_new_row['status']=1;
    $item=$profit_role->where('stage','profits_stage_one')->where('role','OperatingPlatform')->first();
    //平台应得的利息，加上营销机构的剩余利息+融资人提现手续费
    $money=$project->financeTime($item->scale)+$money_marketing_agency-$money_marketing_agency1+$user_fee;
    $money=floor($money*100)/100;
    $user=$bbl_user;
    $orgnaize_user=OrganizationalUser::where('user_id',$user->id)->first();

    //平台分账1%的利润给 ENSURE 保证金户
    // $ensure=$project->financeTime(1);
    // if($money<$ensure){
    //   $ensure=0;
    //   Log::info('平台分润比例小于1%');
    // }else{
    //   $money-=$ensure;
    // }

    $profit_new_row['user_id']=$user->id;
    $profit_new_row['user_name']=$orgnaize_user->company_name;
    $profit_new_row['role_slug']=$item->role;
    $profit_new_row['broker_code']=$user->broker_code;
    $profit_new_row['money']=$money;
    $project_profit[]=$profit_new_row;

    $new_ar=array(0=>$sn,1=>$user->identity_id,4=>$money,6=>'运营平台分润')+$trade_basic_sub;
    ksort($new_ar);
    if($money>0){
      $trade_list[]=$new_ar;
      $trade_data[]=array_merge($trade_sub,array('sn'=>$sn,'receive_user'=>$user->id,'money'=>$money,'remarks'=>'运营平台分润'));
    }

    //保证金账户分润
    // $profit_new_row=$profit_row;
    // $sn=createSn();
    // $profit_new_row['sn']=$sn;
    // $profit_new_row['type']=2;
    // $profit_new_row['pay_time']=$time;
    // $profit_new_row['status']=1;
    
    // $profit_new_row['user_id']=$user->id;
    // $profit_new_row['user_name']=$orgnaize_user->company_name;
    // $profit_new_row['role_slug']=$item->role;
    // $profit_new_row['broker_code']=$user->broker_code;
    // $profit_new_row['money']=$ensure;
    // $project_profit[]=$profit_new_row;
    // $new_ar=array(0=>$sn,1=>config('sinapay.payer_id'),2=>config('sinapay.payer_type'),3=>'ENSURE',4=>$ensure,5=>'',6=>'保证金账户分润');
    // ksort($new_ar);
    // if($ensure>0){
    //   $trade_list[]=$new_ar;
    //   $trade_data[]=array_merge($trade_sub,array('sn'=>$sn,'receive_user'=>$user->id,'money'=>$ensure,'remarks'=>'保证金账户分润'));
    // }


    //第二阶段，投资人
    $item=$profit_role->where('stage','profits_stage_two')->where('role','User')->first();
    //到期还本付息
    if($project->repayment=='sit'){
      foreach ($project_user as $row) {
        $profit_new_row=$profit_row;
        $profit_new_row['sn']=createSn();
        $profit_new_row['type']=1;
        $endtime=time();
        if($project->finance_time_cate=='d'){
          $money=$row->invest_money*$item->scale/100/360*$project->finance_time_num;
          $endtime=strtotime('+'.$project->finance_time_num.' day');
        }
        if($project->finance_time_cate=='m'){
          $money=$row->invest_money*$item->scale/100/360*30*$project->finance_time_num;
          $endtime=strtotime('+'.($project->finance_time_num*30).' day');
        }
        if($project->finance_time_cate=='mm'){
          $money=$row->invest_money*$item->scale/100/12*$project->finance_time_num;
          $endtime=strtotime('+'.$project->finance_time_num.' month');
        }
        $profit_new_row['user_id']=$row->user_id;
        $profit_new_row['user_name']=$row->user_name;
        $profit_new_row['broker_code']=$row->broker_code;
        $profit_new_row['role_slug']=$item->role;
        $profit_new_row['money']=$row->invest_money;
        $profit_new_row['project_user_id']=$row->id;
        $profit_new_row['profit']=round($money,2);
        $profit_new_row['input_time']=date('Y-m-d H:i:s',$endtime);
        $project_profit[]=$profit_new_row;
      }
    }
    //按月还息,到期还本
    if($project->repayment=='month'){
      foreach ($project_user as $row) {
        $profit_new_row=$profit_row;
        $profit_new_row['type']=1;
        $endtime=$date=strtotime($time);
        $user=User::find($row->user_id);
        $endmoney=0;//最后一期的利息

        $profit_new_row['user_id']=$row->user_id;
        $profit_new_row['user_name']=$row->user_name;
        $profit_new_row['role_slug']=$item->role;
        $profit_new_row['project_user_id']=$row->id;
        $profit_new_row['broker_code']=$row->broker_code;
        if($project->finance_time_cate=='d'){
          $money=$row->invest_money*$item->scale/100/360;
          $endmoney=round($money*$project->finance_time_num,2);//总利息
          $num=ceil($project->finance_time_num/30);
          for($i=1;$i<$num;$i++){
            $profit_new_row['sn']=createSn();
            if($i==1){
              if(date('d')>=$code_date){$date=strtotime('+'.$i.' month');}
              $profit_new_row['input_time']=date('Y-m-'.$code_date.' H:i:s',$date);
              $profit_new_row['profit']=floor($money*(strtotime($profit_new_row['input_time'])-$endtime)/3600/24*100)/100;
            }else{
              if(date('d')<$code_date){
                $date=strtotime('+'.($i-1).' month');
              }else{
                $date=strtotime('+'.$i.' month');
              }
              $profit_new_row['input_time']=date('Y-m-'.$code_date.' H:i:s',$date);
              $last_month=strtotime('-1 month',strtotime($profit_new_row['input_time']));
              $profit_new_row['profit']=floor($money*(strtotime($profit_new_row['input_time'])-$last_month)/3600/24*100)/100;
            }
            $project_profit[]=$profit_new_row;
            $endmoney-=$profit_new_row['profit'];
          }
          $endtime=strtotime('+'.$project->finance_time_num.' day');
        }
        if($project->finance_time_cate=='m'){
          $money=$row->invest_money*$item->scale/100/360;
          $endmoney=floor($money*$project->finance_time_num*30*100)/100;//总利息
          $num=ceil($project->finance_time_num);
          $profit_new_row['sn']=createSn();
          for($i=1;$i<$num;$i++){
            if($i==1){
              if(date('d')>=$code_date){$date=strtotime('+'.$i.' month');}
              $profit_new_row['input_time']=date('Y-m-'.$code_date.' H:i:s',$date);
              $profit_new_row['profit']=floor($money*(strtotime($profit_new_row['input_time'])-$endtime)/3600/24*100)/100;
            }else{
              if(date('d')<$code_date){
                $date=strtotime('+'.($i-1).' month');
              }else{
                $date=strtotime('+'.$i.' month');
              }
              $profit_new_row['input_time']=date('Y-m-'.$code_date.' H:i:s',$date);
              $last_month=strtotime('-1 month',strtotime($profit_new_row['input_time']));
              $profit_new_row['profit']=floor($money*(strtotime($profit_new_row['input_time'])-$last_month)/3600/24*100)/100;
            }
            $project_profit[]=$profit_new_row;
            $endmoney-=$profit_new_row['profit'];
          }
          $endtime=strtotime('+'.($project->finance_time_num*30).' day');
        }
        if($project->finance_time_cate=='mm'){
          $profit_new_row['sn']=createSn();
          $money=$row->invest_money*$item->scale/100/12;
          $endmoney=round($money*$project->finance_time_num,2);//总利息
          $num=ceil($project->finance_time_num);
          for($i=1;$i<$num;$i++){
            $date=strtotime('+'.$i.' month');
            $profit_new_row['input_time']=date('Y-m-d H:i:s',$date);
            $profit_new_row['profit']=floor($money*100)/100;
            $project_profit[]=$profit_new_row;
            $endmoney-=$profit_new_row['profit'];
          }
          $endtime=strtotime('+'.$project->finance_time_num.' month');
        }

        $profit_new_row['sn']=createSn();
        $profit_new_row['profit']=$endmoney;
        $profit_new_row['project_user_id']=$row->id;
        $profit_new_row['money']=$row->invest_money;
        $profit_new_row['input_time']=date('Y-m-d H:i:s',$endtime);
        $project_profit[]=$profit_new_row;
      }
    }
    try {
      DB::beginTransaction();
      if(count($trade_list)==0){
        abort(600,'分账参数不能为空');
      }
      //单笔代付到绑定的银行卡(融资人收钱-减去所有的分润金额-提现手续费)
      $sn=createSn();
      $remarks='融资人收钱';
      $money=$project->financed_money-collect($project_profit)->where('type',2)->sum('money');
      $data1=[
        'out_trade_no'=>$sn,
        'out_trade_code'=>'2001',
        'collect_method'=>'binding_card^'.$financier->identity_id.',UID,'.$financier->userInfo->bank_card_id,
        'amount'=>$money,
        'goods_id'=>$project->sn,
        'summary'=>$remarks,
      ];
      $result=CreateSingleHostingPayToCardTrade::send($data1);
      if($result['response_code']!='APPLY_SUCCESS'){abort(600,$result['response_message'].'。交易单号:'.$sn);}

      $financier_item=array('sn'=>$sn,'pay_user'=>0,'receive_user'=>$financier->id,'money'=>$money,'remarks'=>$remarks);
      // $trade_data[]=array_merge($trade_sub,$financier_item);
      $trade_data[]=array_merge($trade_sub,array('sn'=>$sn,'receive_user'=>0,'type'=>5,'pay_user'=>$financier->id,'money'=>$money,'remarks'=>$remarks,'user_fee'=>$user_fee));

      $trade_list_str=array();
      foreach ($trade_list as $item) {
        $trade_list_str[]=implode('~',$item);
      }
      $data=[
        'out_pay_no'=>createSn(),
        'out_trade_code'=>'2001',
        'trade_list'=>implode('$',$trade_list_str),
        'notify_method'=>'single_notify',
        'notify_url'=>config('sinapay.notify_url').'/return/profit'
      ];
      // dump($trade_data);
      // dump($project_profit);
      // foreach (explode('$',$data['trade_list']) as $item) {
      //   dump($item);
      // }
      // dd();
      $result=CreateBatchHostingPayTrade::send($data);
      if($result['response_code']!='APPLY_SUCCESS'){
        abort(600,$result['response_message']);
      }
      //添加流水记录
      TradeRecords::insert($trade_data);
      //添加还款记录
      ProjectProfit::insert($project_profit);
      //更新项目状态
      $project->update(['status'=>'payment']);
      //添加审核记录
      ProjectCheck::insert([
        'project_id'=>$project->id,
        'check_user'=>$login_user->id,
        'input_time'=>$time
      ]);
      //判断投资红包的规则。新手标使用新手标红包
      $rule='gift_grant_rule_3';
      if($project->new_projects){$rule='gift_grant_rule_8';}
      //发放投资红包
      foreach ($project_user as $item) {
        GiftActivity::sendGift($rule,$item->user_id,$time,$item->invest_money,$project->gift_cate);
      }
      DB::commit();
    } catch (Exception $e) {
      DB::rollback();
      Log::info('项目封包异常'.$e->getMessage());
      abort(600,'项目封包异常'.$e->getMessage());
    }
    return redirect('/guarantee/check/'.$id);
  }
  /**
   * 生成借款合同
   * @param  [type] $id 项目编号
   * @return [type]     [description]
   */
  public function createAgreement($id){
    $user=User::user();
    $project=Projects::where('id',$id)->first();
    if(!empty($project->projects_file)){
      return 1;
    }
    $exp='<table cellspacing="0" cellpadding="0" width="340"><tbody><tr class="firstRow"><td width="248" valign="top" style="border-color: black; border-width: 1px; padding: 0px 7px;">
          <p><span style="font-family:宋体">甲方流水号</span></p></td><td width="205" valign="top" style="border-top-color: black; border-right-color: black; border-bottom-color: black; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-style: none; padding: 0px 7px;">
          <p><span style="font-family:宋体">金额（元）</span></p></td></tr>{trs}</tbody></table>';
    $exp_tmp='<tr><td width="248" valign="top" style="border-right-color: black; border-bottom-color: black; border-left-color: black; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: none; padding: 0px 7px;">
          <p><span style="font-family:Tahoma"><span style="background-color: rgb(255, 255, 0);">{user_sn}</span></span>
          </p></td><td width="205" valign="top" style="border-top-style: none; border-left-style: none; border-bottom-color: black; border-bottom-width: 1px; border-right-color: black; border-right-width: 1px; padding: 0px 7px;">
          <p><span style="font-family:Tahoma"><span style="background-color: rgb(255, 255, 0);">{user_money}</span></span>
          </p></td></tr>';
    // if(empty($project)){return 1;}
    $project_user=ProjectsUser::where('projects_id',$id)->get();
    $end_time=time();
    //天
    if($project->finance_time_cate=='d'){
      $end_time=strtotime('+'.$project->finance_time_num.' day');
    }
    //月
    if($project->finance_time_cate=='m'){
      $end_time=strtotime('+'.($project->finance_time_num*30).' day');
    }
    //自然月
    if($project->finance_time_cate=='mm'){
      $end_time=strtotime('+'.$project->finance_time_num.' month');
    }
    $pay_back=date('Y-m-d',$end_time);
    $array=$project->toArray();
    $array['signature']=$user->username;
    $array['pay_back']=$pay_back;
    $array['pay_back_start'] = date('Y-m-d');

    $tmp=Information::where('id',$project->collateral_tmp)->value('content');
    foreach ($array as $key => $value) {
      if(preg_match("/time/",$key)){
        $value=date('Y年m月d日',strtotime($value));
      }
      if(preg_match("/money/",$key)){
        $value=number_format($value,2);
      }
      $tmp=str_replace('{'.$key.'}',$value,$tmp);
    }
    $strs='';
    $trade_list=[];
    foreach ($project_user as $item) {
      $exp1=str_replace('{user_sn}',$item->sn,$exp_tmp);
      $exp1=str_replace('{user_money}',$item->invest_money,$exp1);
      $strs.=$exp1;
      $money=$item->invest_money;
      if($item->gift!=0){
        foreach (explode(',',$item->gift) as $gift) {
          $gift_money=GiftReceive::where('id',$gift)->value('money');
          $money-=$gift_money;
        }
      }
      $sn=createSn();
      $remarks='代收投资金额';
      $row=array($sn,$item->sn,$money,$remarks);
      $trade_list[]=implode('~',$row);
    }
    $exp=str_replace('{trs}',$strs,$exp);
    $tmp=str_replace('{table}',$exp,$tmp);
    
    //代收完成
    $project_user=ProjectsUser::where('projects_id',$id)->get();
    $sn=createSn();
    $remarks='代收完成';
    $sina_data=[
      'out_request_no'=>$sn,
      'trade_list'=>implode('$',$trade_list),
    ];
    $trade_data=array('type'=>8,'project_id'=>$project->id,'sn'=>$sn,'pay_user'=>'','receive_user'=>2,
        'money'=>$project->financed_money,'remarks'=>$remarks,'created_at'=>date('Y-m-d H:i:s'));
    $result=FinishPreAuthTrade::send($sina_data);
    Log::info('代收完成');
    Log::info($result);
    if($result['response_code']!='APPLY_SUCCESS'){
      Log::info($result['response_message']);
      return $result['response_message'];
    }else{
      //添加流水记录
      TradeRecords::insert($trade_data);
      //修改项目信息
      $project->update(['projects_file'=>$tmp,'interest_at'=>date('Y-m-d H:i:s'),'trade_repayment_date'=>$pay_back.' 23:59:59']);
      return 1;
    }
    // return view('web.guarantee.agreement',compact('tmp'));
  }

  /**
   * 机构资产总览
   * 
   * @return [type] [description]
   */
  public function queryMoney(){
    $user = User::user();
    return view('web.guarantee.money',compact('user'));
  }
}